package com.dj.mingkong.portal.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.infrastructure.eo.database.music.BoxEo;
import com.dj.mingkong.common.infrastructure.eo.database.music.BoxVisitEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.music.vo.request.BoxVisitAddVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.BoxVisitCancelVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.BoxVisitQueryVo;
import com.dj.mingkong.portal.biz.controller.music.vo.response.BoxVisitVo;
import com.dj.mingkong.portal.biz.core.base.context.UserContextHolder;
import com.dj.mingkong.portal.biz.repository.database.music.BoxRepository;
import com.dj.mingkong.portal.biz.repository.database.music.BoxVisitRepository;
import com.dj.mingkong.portal.biz.service.music.BoxVisitService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.SecureRandom;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 音乐盒访客管理
 *
 * @author zenglonghui
 * @date: 2023/3/23 17:31
 */
@Slf4j
@Service("boxVisitService")
public class BoxVisitServiceImpl implements BoxVisitService {
    @Resource
    private BoxRepository boxRepository;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserContextHolder userContextHolder;
    @Resource
    private BoxVisitRepository boxVisitRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BoxVisitAddVo addVo) {
        final BoxEo boxEo = boxRepository.getById(addVo.getBoxId());
        AssertUtils.isNotNull(boxEo, "boxId invalid");
        //添加人气
        addPopularity(addVo);
        userContextHolder.getCurrentUserOpt().ifPresent(userInfoContext -> {
            final String key = RedisConstants.VISIT_BOX
                    .concat(userInfoContext.getId().toString())
                    .concat(RedisConstants.KEY_SPLIT)
                    .concat(addVo.getBoxId().toString());
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                saveBoxVisit(key, userInfoContext.getId(), boxEo);
            }
        });
    }

    private void saveBoxVisit(String key, Long userId, BoxEo boxEo) {
        final Optional<BoxVisitEo> optional = boxVisitRepository.oneOptByUserIdAndBoxId(userId, boxEo.getId());
        optional.ifPresentOrElse(boxVisitEo -> {
            log.info("更新访客信息 userId:{}, boxId:{}", userId, boxEo.getId());
            boxVisitRepository.updateById(boxVisitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_BOX, 1, TimeUnit.MINUTES);
        }, () -> {
            log.info("保存访客信息 userId:{}, boxId:{}", userId, boxEo.getId());
            final BoxVisitEo visitEo = BoxVisitEo.builder().userId(userId)
                    .boxId(boxEo.getId()).build();
            boxVisitRepository.save(visitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_BOX, 1, TimeUnit.MINUTES);
            boxRepository.updateById(boxEo.setVisitCount(boxEo.getVisitCount() + 1));
        });
    }

    @Override
    public Page<BoxVisitVo> pageByVo(BoxVisitQueryVo queryVo) {
        return boxVisitRepository.getMapper().listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(BoxVisitCancelVo cancelVo) {
        final BoxEo boxEo = boxRepository.getById(cancelVo.getBoxId());
        AssertUtils.isNotNull(boxEo, "boxId invalid");
        final Optional<BoxVisitEo> optional = boxVisitRepository.oneOptByUserIdAndBoxId(UserContext.getUserId(), cancelVo.getBoxId());
        optional.ifPresent(boxVisitEo -> {
            boxVisitRepository.deleteById(boxVisitEo.getId());
            boxRepository.updateById(boxEo.setVisitCount(boxEo.getVisitCount() - 1));
        });
    }

    private void addPopularity(BoxVisitAddVo boxVisitVo) {
        final var rand = new SecureRandom();
        final long num = rand.nextLong(10) + 1;
        final Long increment = redisTemplate.boundHashOps(RedisConstants.POPULARITY_BOX)
                .increment(boxVisitVo.getBoxId(), num);
        log.info("添加音乐盒人气 id :{}, 点击数： {}", boxVisitVo.getBoxId(), increment);
    }
}
